package com.study.chunguard.common.exception;


import com.study.chunguard.common.exception.code.CodeMsg;
import com.study.chunguard.common.exception.code.ResponseCode;
import lombok.Getter;

/**
 * 业务异常
 *
 * @author zhaowenhao
 * @since 2022-12-27
 */
@Getter
public class BusinessException extends RuntimeException {
    private static final long serialVersionUID = 6610083281801529147L;

    /**
     * 错误码
     * -- GETTER --
     * 获取错误码
     *
     * @return 错误码
     */
    private final Integer code;


    public BusinessException(int code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(Exception e) {
        super(e.getMessage());
        this.code = ResponseCode.FAIL.getCode();
    }

    public BusinessException(String message) {
        this(ResponseCode.FAIL.getCode(), message);
    }

    public BusinessException(CodeMsg codeMsg) {
        this(codeMsg.getCode(), codeMsg.getMsg());
    }

    /**
     * 根据错误码和错误消息构建业务异常
     *
     * @param code    错误码
     * @param message 错误消息
     * @return 业务异常
     */
    public static BusinessException with(int code, String message) {
        return new BusinessException(code, message);
    }

    /**
     * 根据错误消息构建业务异常
     *
     * @param message 错误消息
     * @return 业务异常
     */
    public static BusinessException message(String message) {
        return new BusinessException(message);
    }

    /**
     * 根据错误码与错误消息顶级接口的实现类构建业务异常
     *
     * @param codeMsg 错误码与错误消息顶级接口的实现类
     * @return 业务异常
     */
    public static BusinessException with(CodeMsg codeMsg) {
        return new BusinessException(codeMsg);
    }
}
